package com.shiwaixiangcun.monitor.config;

import com.shiwaixiangcun.monitor.security.MsAuthenticationEntryPoint;
import com.shiwaixiangcun.monitor.security.MsLogoutSuccessHandler;
import com.shiwaixiangcun.monitor.security.MsUserDetailsService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${server.host}")
    private String hostDomain;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()

                .authorizeRequests()
                .antMatchers("/server/static/**", "/mi/**").anonymous()
                .anyRequest().authenticated()
                .and()

                .exceptionHandling()
                .authenticationEntryPoint(new MsAuthenticationEntryPoint("/login.htm"))
                .and()

                .formLogin()
                .loginPage("/login.htm")
                .failureUrl("/login.htm?error=true")
                .permitAll()
                .and()

                .logout()
                .logoutUrl("/logout.htm")
                .logoutSuccessHandler(new MsLogoutSuccessHandler(hostDomain))
                .permitAll();
    }

    @Bean
    public UserDetailsService msUserDetailsService() {
        return new MsUserDetailsService();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}
